<template>
  <div class="app-container-flex">
    <NewFullScreen v-model="showDialog" :title="title" :btn-list="btnList">
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-depotName>
              <el-input
                class="not-mongolia"
                type="input"
                :required="true"
                :disabled="true"
                placeholder="请选择转移仓库"
                v-model="formInfo.data.depotName"
              >
                <template #append>
                  <el-icon @click="selectExportDepot"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-locationNo>
              <el-input
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="请选择转出货位"
                v-model="formInfo.data.locationNo"
              >
                <template #append>
                  <el-icon @click="goodsSearch()">
                    <MoreFilled />
                  </el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-locationTypeValue>
              <el-input
                class="not-mongolia"
                type="input"
                :disabled="true"
                placeholder="转出货位类型"
                v-model="formInfo.data.locationTypeValue"
              />
            </template>
          </page-form>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <page-filter
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button :disabled="!canAddProduct" @click="addProduct"
                >新增行</el-button
              >
            </template>
            <template v-slot:filter-removeProduct>
              <el-button :disabled="!canRemoveProduct" @click="removeProduct"
                >删除行</el-button
              >
            </template>
            <template v-slot:filter-downloadTemplate>
              <el-button @click="downloadTemplate">下载模板</el-button>
            </template>
            <template v-slot:filter-setLocationNo>
              <el-button :disabled="!canRemoveProduct" @click="setLocationNo"
                >批量设置货位</el-button
              >
            </template>
            <template v-slot:filter-uploadFile>
              <el-upload
                :headers="uploadInfo.headers"
                :show-file-list="false"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :before-upload="beforeUpload"
                :action="uploadInfo.action"
                :disabled="!canImportProduct"
              >
                <el-button :disabled="!canImportProduct">导入模板</el-button>
              </el-upload>
            </template>
            <template v-slot:filter-productCodeScan>
              <ScanInputBox
                :query="scanInfo.query"
                :api="scanInfo.api"
                :disabled="!canAddProduct"
                @callback="onCallBackScanData"
              />
            </template>
          </page-filter>
          <div class="flex_full_item">
            <!-- 表格 -->
            <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
              <page-table
                :class="{
                  isShow:
                    selectProductInfo.popoVisible ||
                    selectBatchInfo.popoVisible,
                }"
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summaryFieldList="tableInfo.summaryFieldList"
                :tabIndex="false"
                :check-box="true"
                :spanMethod="spanMethod"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :cell-class-name="tableCellClassName"
                :isDynamic="true"
                methodKey="groupKey"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-commonName="scope">
                  <el-input
                    v-if="
                      scope.row.emptyRowType && scope.row.emptyRowType === '1'
                    "
                    :ref="'productRef' + scope.$index"
                    :class="'productKey' + scope.$index"
                    class="productKey"
                    :disabled="
                      !formInfo.data.depotId || !formInfo.data.locationNo
                    "
                    v-model="scope.row.productKeyword"
                    placeholder="名称\编码\规格\批号"
                    @keyup.enter="productSearchInput(scope.row, scope.$index)"
                  >
                    <template #append>
                      <div
                        class="el-input-search"
                        @click="productSearch(scope.row, scope.$index)"
                      >
                        <el-icon style="vertical-align: middle">
                          <Search />
                        </el-icon>
                      </div>
                    </template>
                  </el-input>
                  <span v-else>{{ scope.row.commonName }}</span>
                </template>
                <template v-slot:col-storeBatchNumber="scope">
                  <el-input
                    v-if="
                      scope.row.emptyRowType &&
                      (scope.row.emptyRowType === '1' ||
                        scope.row.emptyRowType === '2') &&
                      (!scope.row.codeType ||
                        scope.row.codeType === 1 ||
                        scope.row.codeType === 4)
                    "
                    :ref="'batchRef' + scope.$index"
                    :class="'batchKey' + scope.$index"
                    class="batchKey"
                    placeholder="入库批次\供应商名称"
                    :disabled="!scope.row.commonName"
                    v-model="scope.row.batchKeyword"
                    @keyup.enter="
                      batchNumberSearchInput(scope.row, scope.$index)
                    "
                  >
                    <template #append>
                      <div
                        class="el-input-search"
                        @click="batchNumberSearch(scope.row, scope.$index)"
                      >
                        <el-icon style="vertical-align: middle">
                          <Search />
                        </el-icon>
                      </div>
                    </template>
                  </el-input>
                  <template v-else>
                    <span
                      v-if="
                        scope.row.codeType === 2 || scope.row.codeType === 3
                      "
                      >-</span
                    >
                    <StoreBatchNumberTag v-else :row="scope.row" />
                  </template>
                </template>
                <template v-slot:col-supplierName="scope">
                  <span
                    v-if="scope.row.codeType === 2 || scope.row.codeType === 3"
                    >-</span
                  >
                  <span v-else>{{ scope.row['supplierName'] }}</span>
                </template>
                <template v-slot:col-qty="scope">
                  <el-form-item
                    class="margin-bottom"
                    v-if="
                      (scope.row.codeType === 1 || scope.row.codeType === 4) &&
                      !scope.row.emptyRowType
                    "
                  >
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            :prop="`data.${scope.$index}.largeUnitQty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.largeUnitQty"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              @change="
                                changeLarge(
                                  $event,
                                  scope.row,
                                  `data.${scope.$index}.largeUnitQty`
                                )
                              "
                              :min="0"
                              :max="largeMax(scope.row)"
                            />
                          </el-form-item>
                          <!-- <div class="page-table-input-number-item-unite">
                            {{ scope.row.unitName }}
                          </div> -->
                        </div>
                        <div
                          class="page-table-input-number-item"
                          v-if="
                            scope.row.unitConvertCoefficient > 1 &&
                            scope.row.qtyOperateMode === 2
                          "
                        >
                          <el-form-item>
                            <el-input-number
                              style="width: 100%; margintop: 18px"
                              v-model.lazy="scope.row.smallUnitQty"
                              clearable
                              controls-position="right"
                              :precision="0"
                              :min="0"
                              :max="smallMax(scope.row)"
                              @change="
                                changeSmall(
                                  $event,
                                  scope.row,
                                  `data.${scope.$index}.smallUnitQty`
                                )
                              "
                            />
                          </el-form-item>
                          <!-- <div class="page-table-input-number-item-unite">
                            {{ scope.row.calcUnitName }}
                          </div> -->
                        </div>
                      </div>
                      <div
                        class="page-table-input-number-right"
                        v-if="scope.row.qtyOperateMode === 2"
                      >
                        {{ $fn.qtyFormatter(scope.row.qty) }}
                      </div>
                    </div>
                  </el-form-item>
                  <span
                    v-else-if="
                      (scope.row.codeType === 2 || scope.row.codeType === 3) &&
                      !scope.row.emptyRowType
                    "
                    >{{ $fn.qtyFormatter(scope.row.qty) }}</span
                  >
                </template>
                <template v-slot:col-targetLocationNo="scope">
                  <el-form-item
                    v-if="scope.row.commonName"
                    :prop="`data.${scope.$index}.targetLocationNo`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              required: true,
                              trigger: 'change',
                              message: '请选择转入货位',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input
                      :ref="'targetLocationNoRef' + scope.$index"
                      :class="'targetLocationNo' + scope.$index"
                      class="targetLocationNo not-mongolia"
                      disabled
                      v-model="scope.row.targetLocationNo"
                      placeholder="请选择转入货位"
                      @keyup.enter="
                        goodsSearch(scope.row, scope.$index, 'enter')
                      "
                    >
                      <template #append>
                        <div
                          class="el-input-search"
                          @click="goodsSearch(scope.row, scope.$index)"
                        >
                          <el-icon style="vertical-align: middle">
                            <Search />
                          </el-icon>
                        </div>
                      </template>
                    </el-input>
                  </el-form-item>
                  <!-- <span v-else>{{ scope.row.targetLocationNo }}</span> -->
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
  </div>
  <!-- 选择产品 -->
  <SelectProduct
    v-if="selectProductInfo.visible"
    v-model:showDialog="selectProductInfo.visible"
    :tableKey="selectProductInfo.tableKey"
    :query="selectProductInfo.query"
    :highlightRow="false"
    :checkBox="true"
    :showPrice="$permission('cargoSpaceTransfer:price')"
    :api="selectProductInfo.api"
    @callback="selectProductBackList"
  />
  <!-- 选择批次 -->
  <SelectBatch
    v-if="selectBatchInfo.visible"
    v-model:showDialog="selectBatchInfo.visible"
    :popoVisible="selectBatchInfo.visible"
    :tableKey="selectBatchInfo.tableKey"
    :query="selectBatchInfo.query"
    :codeType="selectBatchInfo.row.codeType"
    :highlightRow="false"
    :checkBox="true"
    :showPrice="$permission('cargoSpaceTransfer:price')"
    :api="selectBatchInfo.api"
    @callback="selectBatchBackList"
  ></SelectBatch>
  <!-- 转移仓库 -->
  <SelectDepot
    v-if="selectExportDepotInfo.visible"
    v-model:showDialog="selectExportDepotInfo.visible"
    :checkBox="false"
    :query="selectExportDepotInfo.query"
    :highlightRow="true"
    :checkLock="true"
    :saveEmpty="true"
    @callback="selectExportDepotCallBack"
  />
  <!-- 转出货位或转入货位 -->
  <SelectGoods
    v-if="selectGoodsInfo.visible"
    v-model:show-dialog="selectGoodsInfo.visible"
    :query="selectGoodsInfo.query"
    :check-box="false"
    :highlightRow="true"
    :api="selectGoodsInfo.api"
    @callback="selectGoodsCallback"
  />
  <SelectGoods
    v-if="setGoodsInfo.visible"
    v-model:show-dialog="setGoodsInfo.visible"
    :query="setGoodsInfo.query"
    :check-box="false"
    :highlightRow="true"
    :api="setGoodsInfo.api"
    @callback="setGoodsCallback"
  />
  <el-popover
    v-if="selectProductInfo.popoVisible"
    ref="productPopoverRef"
    popper-class="popover-wrapper"
    placement="bottom-start"
    :virtual-ref="productRef"
    width="1000px"
    :visible="selectProductInfo.popoVisible"
    virtual-triggering
    @hide="productPopoHide"
  >
    <ProductTable
      v-if="selectProductInfo.popoVisible"
      :popoVisible="selectProductInfo.popoVisible"
      :tableKey="selectProductInfo.tableKey"
      :query="selectProductInfo.query"
      :highlightRow="selectProductInfo.highlightRow"
      :checkBox="selectProductInfo.checkBox"
      :refresh="selectProductInfo.refresh"
      :showPrice="$permission('cargoSpaceTransfer:price')"
      :api="selectProductInfo.api"
      tableType="product"
      @checkMore="checkMore('product')"
      @reset="selectProductInfo.popoVisible = false"
      @callback="selectProductBack"
      @keyDown="productKeyDown"
    ></ProductTable>
  </el-popover>
  <el-popover
    v-if="selectBatchInfo.popoVisible"
    ref="batchPopoverRef"
    :virtual-ref="batchRef"
    popper-class="popover-wrapper"
    placement="bottom-start"
    width="600px"
    :visible="selectBatchInfo.popoVisible"
    virtual-triggering
    @hide="batchPopoHide"
  >
    <ProductTable
      v-if="selectBatchInfo.popoVisible"
      :popoVisible="selectBatchInfo.popoVisible"
      :tableKey="selectBatchInfo.tableKey"
      :query="selectBatchInfo.query"
      :highlightRow="selectBatchInfo.highlightRow"
      :checkBox="selectBatchInfo.checkBox"
      :refresh="selectBatchInfo.refresh"
      :showPrice="$permission('cargoSpaceTransfer:price')"
      :codeType="selectBatchInfo.row.codeType"
      :api="selectBatchInfo.api"
      tableType="batch"
      @checkMore="checkMore('batch')"
      @reset="selectBatchInfo.popoVisible = false"
      @callback="selectBatchBack"
      @keyDown="batchKeyDown"
    ></ProductTable>
  </el-popover>
  <el-popover
    v-if="selectGoodsInfo.popoVisible"
    ref="targetPopoverLocationNoRef"
    popper-class="popover-wrapper"
    placement="bottom-start"
    width="600px"
    :virtual-ref="targetLocationNoRef"
    :visible="selectGoodsInfo.popoVisible"
    virtual-triggering
    @hide="goodsPopoHide"
  >
    <ProductGoods
      v-if="selectGoodsInfo.popoVisible"
      :api="selectGoodsInfo.api"
      :query="selectGoodsInfo.query"
      :highlightRow="selectGoodsInfo.highlightRow"
      :checkBox="selectGoodsInfo.checkBox"
      :refresh="selectGoodsInfo.refresh"
      @checkMore="checkMore('goods')"
      @reset="selectGoodsInfo.popoVisible = false"
      @callback="selectGoodsCallback"
      @keyDown="goodsKeyDown"
    ></ProductGoods>
  </el-popover>
  <BatchIndividual
    v-if="individualInfo.visible"
    v-model:visible="individualInfo.visible"
    :leftApi="individualInfo.leftApi"
    :rightApi="individualInfo.rightApi"
    :leftTableKey="individualInfo.leftTableKey"
    :rightTableKey="individualInfo.rightTableKey"
    :leftQuery="individualInfo.leftQuery"
    :rightQuery="individualInfo.rightQuery"
    :details="individualInfo.details"
    :isRequest="individualInfo.isRequest"
    :isGetRightList="!!orderId"
    :showPrice="$permission('cargoSpaceTransfer:price')"
    @callback="individualCallback"
  ></BatchIndividual>
</template>

<script setup name="cargoSpaceTransferModify">
import SelectProduct from '@/views/wms/components/SelectProduct'
import SelectBatch from '@/views/wms/components/SelectBatch'
import BatchIndividual from '@/views/wms/components/BatchIndividual'
import ProductTable from '@/views/wms/components/ProductTable'
import ScanInputBox from '@/views/wms/components/ScanInputBox'
import StoreBatchNumberTag from '@/views/wms/components/StoreBatchNumberTag'
import ProductGoods from './productGoods'
import {
  goodsLocationPage,
  getShelfStockCustomizeListPage,
  addTransferOrder,
  updateTransferOrder,
  shelfStockNum,
  transferOrderById,
  getConsumeOrderDetailCustomizeListAll,
  getDepotStockCustomizeListPage,
  shelfStockCustomizeScanWithConsume,
} from '@/api/wms'
import { getCustomizeSetting } from '@/api/customize'
import { exportTemplateExcel } from '@/api/pub.js'
import moment from 'moment'
import _ from 'lodash'
import { setVal, setTabindex } from '@/common/js/base'
import { ElLoading } from 'element-plus'
const { proxy } = getCurrentInstance()
const emit = defineEmits()
const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))
const SetPreference = defineAsyncComponent(() =>
  import('@/components/SetPreference/setPreferenceNoQuery')
)
const SelectGoods = defineAsyncComponent(() => import('./selectGoods'))

const props = defineProps({
  visible: {
    type: Boolean,
  },
  title: {
    type: [String, Number],
  },
  orderId: {
    type: [String, Number],
  },
})
const productPopoverRef = ref()
const productRef = ref()
const batchPopoverRef = ref()
const batchRef = ref()
const targetLocationNoRef = ref()
const targetPopoverLocationNoRef = ref()
const formRefs = ref([])
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const btnList = ref([{ label: '保存', event: save, show: true }])
const slipSelectRequest = ref(true)
const scanInfo = ref({
  api: shelfStockCustomizeScanWithConsume,
  query: {
    queryMap: {
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    customizeUserVO: {},
    queryParams: {
      depotId: '',
      goodsLocationId: '',
      locationNo: '',
      isSelectMerge: 1,
      // validateExpire: false
    },
  },
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {
      isSelectMerge: 1,
    },
  },
  list: [
    { type: 'slot', value: 'addProduct' },
    { type: 'slot', value: 'removeProduct' },
    { type: 'slot', value: 'downloadTemplate' },
    { type: 'slot', value: 'uploadFile' },
    { type: 'slot', value: 'setLocationNo' },
    { type: 'slot', value: 'productCodeScan' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  sysGroup: [],
  productSysGroup: [],
  data: [
    {
      emptyRowType: '1', //1添加产品和批次，2添加批次
      productKeyword: '',
      batchKeyword: '',
      id: new Date().getTime() + (1 + Math.random()),
    },
  ],
  tabList: [],
  tabIndex: 0,
  selections: [],
  summaryFieldList: [{ value: 'qty', formatter: proxy.$fn.qtyFormatter }],
  fieldList: [
    {
      label: '通用名称',
      value: 'commonName',
      type: 'slot',
      minWidth: '100px',
    },
    {
      label: '产品编码',
      value: 'productCode',
      width: '100px',
    },
    {
      label: '规格',
      value: 'standard',
    },
    {
      label: '厂家',
      value: 'brandName',
      width: '80px',
    },
    {
      label: '单位',
      value: 'unitName',
      width: '80px',
    },
    // {
    //   label: '条码类型',
    //   value: 'codeTypeValue',
    // },
    {
      label: '批号',
      value: 'batchNumber',
    },
    {
      label: '生产日期',
      value: 'productionDate',
      width: '80px',
    },
    {
      label: '失效日期',
      value: 'validityDate',
      width: '80px',
    },
    {
      label: '入库批次号',
      value: 'storeBatchNumber',
      type: 'slot',
      align: 'left',
      minWidth: '100px',
    },
    {
      label: '供应商',
      value: 'supplierName',
      type: 'slot',
    },
    {
      label: '单价',
      value: 'price',
      type: 'column',
      formatter: (row, column, cellValue, index) => {
        if (row.codeType === 2 || row.codeType === 3) return '-'
        return proxy.$fn.TripartiteMethod(row, column, cellValue, index)
      },
      permission: !proxy.$permission('cargoSpaceTransfer:price'),
      width: '60px',
    },
    {
      label: '可用数',
      value: 'stockAvailableQty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
      width: '60px',
    },
    {
      label: '转移数量',
      value: 'qty',
      type: 'slot',
    },
    {
      label: '转入货位',
      value: 'targetLocationNo',
      type: 'slot',
      minWidth: '100px',
    },
    {
      label: '转入货位类型',
      value: 'targetLocationTypeValue',
    },
  ],
  handle: {
    fixed: 'right',
    label: '批次操作',
    width: '120',
    btList: [
      {
        label: '个体详情',
        event: individualDetails,
        show: true,
        ifRender: function (row) {
          let arr = [2, 3]
          return arr.includes(row.codeType) && row.emptyRowType !== '1'
        },
      },
      {
        label: '新增',
        event: addBucth,
        show: true,
        ifRender: ifRenderAddButch,
      },
      {
        label: '复制',
        event: copyBucth,
        show: true,
        ifRender: ifRenderCopyButch,
      },
      {
        label: '删除',
        event: removeBatch,
        show: true,
        ifRender: function (row) {
          return !row.emptyRowType
        },
      },
    ],
  },
  bigWidth: {
    productCode: '100px',
    standard: '60px',
    brandName: '80px',
    unitName: '80px',
    batchNumber: '100px',
    productionDate: '80px',
    validityDate: '80px',
    supplierName: '80px',
    price: '80px',
    stockAvailableQty: '60px',
    qty: '80px',
    targetLocationTypeValue: '90px',
  },
  smallWidth: {
    productCode: '90px',
    standard: '60px',
    brandName: '60px',
    unitName: '40px',
    batchNumber: '60px',
    productionDate: '50px',
    validityDate: '80px',
    supplierName: '60px',
    price: '50px',
    stockAvailableQty: '50px',
    qty: '80px',
    targetLocationTypeValue: '50px',
  },
})
const selectProductInfo = ref({
  visible: false,
  popoVisible: false,
  refresh: 1,
  row: {},
  index: 0,
  query: {
    excludeQueryList: [],
    queryMap: {
      depotId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      goodsLocationId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    //isEstimationStockBusiness 这个需要传，如果不传会过滤掉暂估库存
    queryParams: {
      isShelfSearchLeft: 1,
      stockSearchKey: '',
      isEstimationStockBusiness: 1,
    },
  },
  tableKey:
    'selectProductStockTransferOrder-com.slip.spd.entity.vo.wms.WmsShelfStockVO',
  highlightRow: true,
  checkBox: false,
  api: getShelfStockCustomizeListPage,
})
const selectGoodsInfo = ref({
  visible: false,
  api: goodsLocationPage,
  query: {
    status: '1',
    deportId: '',
    idNotIn: '',
  },
  popoVisible: false,
  refresh: 1,
  row: {},
  index: 0,
  highlightRow: true,
  checkBox: false,
})
const setGoodsInfo = ref({
  visible: false,
  api: goodsLocationPage,
  query: {
    status: '1',
    deportId: '',
    idNotIn: '',
  },
})
const selectBatchInfo = ref({
  visible: false,
  popoVisible: false,
  refresh: 1,
  row: {},
  index: 0,
  query: {
    queryMap: {
      depotId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      orgId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      productId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      batchNumber: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      productionDate: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      validityDate: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      goodsLocationId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {
      isShelfSearchRight: 1,
      stockSearchKey: '',
      groupField: '',
      isEstimationStockBusiness: 1,
    },
  },
  tableKey:
    'selectBatchStockConsumeOrder-com.slip.spd.entity.vo.wms.WmsShelfStockVO',
  highlightRow: true,
  checkBox: false,
  api: shelfStockNum,
})
const selectExportDepotInfo = ref({
  visible: false,
  query: {
    depotAuth: 'id',
    useTypeId: '1',
    status: 1,
    isCargoSpaceManage: 1,
  },
})
const individualInfo = ref({
  visible: false,
  isRequest: false,
  row: {},
  details: [],
  rightVo: {},
  index: '',
  leftQuery: {
    queryMap: {
      id: {
        queryType: 'NOT_IN',
        queryCategory: 'AND',
        value: null,
      },
      orgId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      productId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      batchNumber: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      productionDate: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      validityDate: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        ignoreEmptyValue: false,
        value: null,
      },
      depotId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      goodsLocationId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
    },
    queryParams: {
      isShelfSearchRight: 1,
      groupField: '',
      isEstimationStockBusiness: 1,
    },
  }, //个体弹窗左边数据查询条件
  rightQuery: {
    queryMap: {
      isConsignBusiness: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: '',
      },
      id: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: null,
      },
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
      depotId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: null,
      },
    },
    queryParams: {},
  },
  leftTableKey:
    'selectProductStockTransferOrderIndividualLeft-com.slip.spd.entity.vo.wms.WmsShelfStockVO',
  rightTableKey:
    'selectProductStockTransferOrderIndividualRight-com.slip.spd.entity.vo.wms.WmsTransferOrderVO',
  rightApi: getConsumeOrderDetailCustomizeListAll, //个体弹窗右边数据接口
  leftApi: getDepotStockCustomizeListPage, //个体弹窗左边数据接口
})
//表单相关
const formInfo = ref({
  ref: null,
  data: {
    depotName: proxy.$store.state.user.userInfo.coreResourcesVO
      ?.isCargoSpaceManage
      ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceName
      : '',
    depotId: proxy.$store.state.user.userInfo.coreResourcesVO
      ?.isCargoSpaceManage
      ? proxy.$store.state.user.userInfo.coreResourcesVO.resourceId
      : '',
    locationTypeValue: '',
    goodsLocationId: '',
    locationNo: '',
  },
  fieldList: [
    { label: '转移仓库', value: 'depotName', type: 'slot' },
    {
      label: '转出货位',
      value: 'locationNo',
      type: 'slot',
    },
    {
      label: '转出货位类型',
      value: 'locationTypeValue',
      type: 'input',
      placeholder: '转出货位类型',
      disabled: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'input',
      clearable: false,
    },
  ],
  rules: {
    depotName: [{ required: true, message: '请选择仓库', trigger: 'change' }],
    locationNo: [
      { required: true, message: '请选择消耗部门', trigger: 'change' },
    ],
  },
  labelWidth: '120px',
})
const uploadInfo = ref({
  action: '',
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
})
// 唯一码
const groupField1 = ref('')
// 批次码 无码
const groupField2 = ref('')

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length) {
      let list = []
      tableInfo.value.data.forEach((item, index) => {
        if (item.emptyRowType && item.emptyRowType === '1') {
          let arr = [
            { key: 'productKey' + index, index: index },
            { key: 'batchKey' + index, index: index },
          ]
          list = list.concat(arr)
        } else if (item.emptyRowType && item.emptyRowType === '2') {
          list.push({ key: 'batchKey' + index, index: index })
        }
        // let cargoStockIds = []
        // if (item.details && item.details.length) {
        //   cargoStockIds = item.details.map((el) => el.cargoStockId)
        // } else {
        //   if (item.groupConcatCargoStockIds) {
        //     cargoStockIds.push(item.groupConcatCargoStockIds)
        //   }
        // }
        // item.groupConcatCargoStockIds = cargoStockIds.length
        //   ? cargoStockIds.toString()
        //   : ''
      })
      tableInfo.value.tabList = list
      setTabindex(proxy)
      setSuplierIdMap()
    }
  },
  { deep: true }
)
watch(
  () => selectBatchInfo.value.popoVisible,
  (val) => {
    if (val) {
      selectProductInfo.value.popoVisible = false
    }
  }
)
watch(
  () => selectProductInfo.value.popoVisible,
  (val) => {
    if (val) {
      selectBatchInfo.value.popoVisible = false
    }
  }
)
window.addEventListener('click', closePopper, { passive: true })
window.addEventListener('keydown', addTab, true)
onActivated(() => {
  window.addEventListener('click', closePopper, { passive: true })
  window.addEventListener('keydown', addTab, true)
})
onDeactivated(() => {
  window.removeEventListener('click', closePopper, true)
  window.removeEventListener('keydown', addTab, true)
})

function addTab(val) {
  if (val.key === 'Tab') {
    if (!formInfo.value.data.depotId) {
      selectExportDepot()
      return
    }
  }
}
function closePopper(e) {
  if (
    e.target.closest('.el-popper') ||
    e.target.closest('.productKey') ||
    e.target.closest('.batchKey') ||
    e.target.closest('.targetLocationNo')
  ) {
    // 点击当前元素处理操作
  } else {
    //点击非当前元素，需要执行的代码
    selectBatchInfo.value.popoVisible = false
    selectProductInfo.value.popoVisible = false
    selectGoodsInfo.value.popoVisible = false
  }
}
const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canAddProduct = computed(() => {
  return formInfo.value.data.depotId && formInfo.value.data.locationNo
})
const canImportProduct = computed(() => {
  return (
    formInfo.value.data.depotId &&
    formInfo.value.data.locationNo &&
    tableInfo.value.data.length <= 1
  )
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})

onMounted(() => {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  proxy.$nextTick(() => {
    if (!props.orderId) {
      formInfo.value.fieldList = formInfo.value.fieldList.filter(
        (item) => item.value !== 'orderNo'
      )
    }
  })
  proxy.$fn.setFieldListColWidth(
    tableInfo.value.fieldList,
    tableInfo.value.bigWidth,
    tableInfo.value.smallWidth
  )
})
function spanMethod({ row, column, rowIndex, columnIndex }) {
  let len = tableInfo.value.fieldList.length
  if (row.emptyRowType !== '1' || !row.emptyRowType) {
    const afterIndexs = []
    let keys = new Array(len + 2)
    if (afterIndexs.length && afterIndexs.includes(columnIndex)) {
      keys[columnIndex] = 'groupKey'
    } else {
      keys = [
        'groupKey',
        'commonName',
        'productCode',
        'standard',
        'brandName',
        'unitName',
        // 'codeTypeValue',
        'batchNumber',
        'productionDate',
        'validityDate',
      ]
    }
    // 注意:字段列表要按表格排列的顺序排列,如果后续字段不再需要进行行合并,可以省略后面的字段,如果中间某字段要跳过合并,要用空字符串顶位
    return proxy.$fn.spanMethod(
      tableInfo.value.data,
      keys,
      rowIndex,
      columnIndex
    )
  }
}
function ifRenderAddButch(row) {
  if (!row.commonName) return false
  let list = tableInfo.value.data.filter(
    (item) => item.groupKey === row.groupKey
  )
  let index = list.lastIndexOf(row)
  return index === list.length - 1
}
function ifRenderCopyButch(row) {
  let arr = [1, 4]
  if (arr.includes(row.codeType) && !row.emptyRowType) {
    return true
  }
}
//新增行
function addProduct() {
  tableInfo.value.data.push({
    emptyRowType: '1',
    productKeyword: '',
    batchKeyword: '',
    id: new Date().getTime() + (1 + Math.random()),
  })
}
function checkMore(str) {
  if (str === 'product') {
    let row = selectProductInfo.value.row
    let index = selectProductInfo.value.index
    productSearch(row, index)
  } else if (str === 'batch') {
    let row = selectBatchInfo.value.row
    let index = selectBatchInfo.value.index
    batchNumberSearch(row, index)
  } else if (str === 'goods') {
    let row = selectGoodsInfo.value.row
    let index = selectGoodsInfo.value.index
    goodsSearch(row, index)
  }
}
function productSearch(row, index) {
  if (!formInfo.value.data.locationNo) {
    return
  }
  //产品点击查询图标
  if (!formInfo.value.data.depotId) {
    selectExportDepot()
    return
  }
  selectProductInfo.value.query.queryParams.stockSearchKey = row.productKeyword
  selectProductInfo.value.query.queryMap.goodsLocationId.value =
    formInfo.value.data.goodsLocationId
  selectProductInfo.value.row = row
  selectProductInfo.value.index = index
  let key = []
  tableInfo.value.data.forEach((row) => {
    if (!row.emptyRowType || row.emptyRowType === '2') {
      let arr = []
      tableInfo.value.productSysGroup.forEach((item) => {
        let obj = {}
        obj.columnName = item.columnName
        obj.asTbName = item.asTbName
        obj.value = row[item.key]
        arr.push(obj)
      })
      key.push(arr)
    }
  })
  selectProductInfo.value.query.excludeQueryList = key
  selectProductInfo.value.visible = true
  selectProductInfo.value.popoVisible = false
}
function productSearchInput(row, index) {
  //产品enter查询
  if (!formInfo.value.data.depotId) {
    selectExportDepot()
    return
  }
  productRef.value = proxy.$refs['productRef' + index]
  selectProductInfo.value.query.queryParams.stockSearchKey = row.productKeyword
  selectProductInfo.value.query.queryMap.goodsLocationId.value =
    formInfo.value.data.goodsLocationId
  selectProductInfo.value.refresh = Math.random()
  selectProductInfo.value.row = row
  selectProductInfo.value.index = index
  let key = []
  tableInfo.value.data.forEach((row) => {
    if (!row.emptyRowType || row.emptyRowType === '2') {
      let arr = []
      tableInfo.value.productSysGroup.forEach((item) => {
        let obj = {}
        obj.columnName = item.columnName
        obj.asTbName = item.asTbName
        obj.value = row[item.key]
        arr.push(obj)
      })
      key.push(arr)
    }
  })
  selectProductInfo.value.query.excludeQueryList = key
  selectProductInfo.value.popoVisible = true
}
function productKeyDown(index) {
  proxy.$nextTick(() => {
    if (index < 0) {
      let className = 'productKey' + selectProductInfo.value.index
      setVal(className)
      selectProductInfo.value.popoVisible = false
      return
    }
    let className = 'productKey' + selectProductInfo.value.index
    let productKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector('.el-input__inner')
    productKeyDom.blur()
  })
}
function selectProductBack(obj) {
  let index = selectProductInfo.value.index
  if (obj.groupConcatIds.includes(',')) {
    tableInfo.value.data[index] = {
      commonName: obj.commonName,
      productCode: obj.productCode,
      groupKey: obj.groupKey,
      standard: obj.standard,
      brandName: obj.brandName,
      brandId: obj.brandId,
      unitName: obj.unitName,
      unitId: obj.unitId,
      codeTypeValue: obj.codeTypeValue,
      codeType: obj.codeType,
      batchNumber: obj.batchNumber,
      productionDate: obj.productionDate,
      validityDate: obj.validityDate,
      depotStockId: obj.depotStockId,
      orgId: obj.orgId,
      productId: obj.productId,
      emptyRowType: '2',
      cargoStockId: obj.cargoStockId,
    }
    // if (obj.codeType === 1 || obj.codeType === 4) {
    //   batchNumberSearchInput(tableInfo.value.data[index], index)
    // } else if (obj.codeType === 2 || obj.codeType === 3) {
    //   batchNumberSearch(tableInfo.value.data[index], index)
    // }
  } else {
    obj = countData(obj)
    tableInfo.value.data[index] = proxy.$fn.deepClone(obj)
    tableInfo.value.data[index].details = [proxy.$fn.deepClone(obj)]
  }
  let itemList = tableInfo.value.data.filter(
    (item) => item.emptyRowType === '1'
  )
  if (!itemList.length) {
    tableInfo.value.data.push({
      emptyRowType: '1',
      productKeyword: '',
      batchKeyword: '',
      id: new Date().getTime() + (1 + Math.random()),
    })
  }
}
function selectProductBackList(data) {
  let index = selectProductInfo.value.index
  let newData = data.map((item) => {
    if (item.groupConcatIds.includes(',')) {
      return {
        commonName: item.commonName,
        productCode: item.productCode,
        groupKey: item.groupKey,
        standard: item.standard,
        brandName: item.brandName,
        brandId: item.brandId,
        unitName: item.unitName,
        unitId: item.unitId,
        codeTypeValue: item.codeTypeValue,
        codeType: item.codeType,
        batchNumber: item.batchNumber,
        productionDate: item.productionDate,
        validityDate: item.validityDate,
        depotStockId: item.depotStockId,
        productId: item.productId,
        orgId: item.orgId,
        emptyRowType: '2',
      }
    } else {
      item = countData(item)
      item.details = [proxy.$fn.deepClone(item)]
      return item
    }
  })
  let emptyRowTypeList = tableInfo.value.data.filter(
    (item) => item.emptyRowType === '1'
  ) //空行条数
  let list = proxy.$fn.deepClone(tableInfo.value.data)
  let leftList,
    rightList = []
  if (emptyRowTypeList.length > 1) {
    if (index === tableInfo.value.data.length - 1) {
      //是否最后一条
      leftList = list.slice(0, index)
      rightList = list.slice(index)
    } else {
      leftList = list.slice(0, index)
      rightList = list.slice(index + 1)
    }
  } else {
    leftList = list.slice(0, index)
    rightList = list.slice(index)
  }
  tableInfo.value.data = leftList.concat(newData).concat(rightList)
}
function productPopoHide() {
  selectProductInfo.value.popoVisible = false
}
function batchNumberSearch(row, index) {
  if (!row.commonName) return
  let groupKeyList = tableInfo.value.data.filter(
    (item) => item.groupKey === row.groupKey
  )
  if (groupKeyList.length && (row.codeType === 2 || row.codeType === 3)) {
    let ids = []
    groupKeyList.forEach((item) => {
      if (!item.details) {
        ids.push(item.groupConcatCargoStockIds)
      } else {
        item.details.forEach((el) => {
          ids.push(el.cargoStockId)
        })
      }
    })
    selectBatchInfo.value.query.queryMap.id.value = ids.toString()
  } else {
    selectBatchInfo.value.query.queryMap.id.value = null
  }
  selectBatchInfo.value.query.queryParams.stockSearchKey = row.batchKeyword
  selectBatchInfo.value.row = row
  selectBatchInfo.value.index = index
  selectBatchInfo.value.query.queryMap.orgId.value = row.orgId
  selectBatchInfo.value.query.queryMap.productId.value = row.productId
  selectBatchInfo.value.query.queryMap.goodsLocationId.value =
    formInfo.value.data.goodsLocationId
  if (row.batchNumber) {
    selectBatchInfo.value.query.queryMap.batchNumber = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.batchNumber,
    }
  } else {
    selectBatchInfo.value.query.queryMap.batchNumber = {
      queryType: 'NULL',
      queryCategory: 'AND',
      value: '',
    }
  }
  if (row.validityDate) {
    selectBatchInfo.value.query.queryMap.validityDate = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.validityDate,
    }
  } else {
    selectBatchInfo.value.query.queryMap.validityDate = {
      queryType: 'NULL',
      ignoreEmptyValue: false,
      queryCategory: 'AND',
      value: null,
    }
  }
  if (row.productionDate) {
    selectBatchInfo.value.query.queryMap.productionDate = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.productionDate,
    }
  } else {
    selectBatchInfo.value.query.queryMap.productionDate = {
      queryType: 'NULL',
      ignoreEmptyValue: false,
      queryCategory: 'AND',
      value: null,
    }
  }
  if (row.codeType === 2 || row.codeType === 3) {
    selectBatchInfo.value.query.queryParams.groupField = groupField1.value
  } else {
    selectBatchInfo.value.query.queryParams.groupField = groupField2.value
  }
  selectBatchInfo.value.visible = true
  selectBatchInfo.value.popoVisible = false
}
function batchNumberSearchInput(row, index) {
  //批次enter查询
  let timer = setTimeout(() => {
    let className = 'batchKey' + index
    let batchKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector('.el-input__inner')
    batchKeyDom.focus()
    batchRef.value = proxy.$refs['batchRef' + index]
    selectBatchInfo.value.query.queryParams.stockSearchKey = row.batchKeyword
    selectBatchInfo.value.refresh = Math.random()
    selectBatchInfo.value.row = row
    selectBatchInfo.value.index = index
    selectBatchInfo.value.query.queryMap.orgId.value = row.orgId
    selectBatchInfo.value.query.queryMap.productId.value = row.productId
    selectBatchInfo.value.query.queryMap.goodsLocationId.value =
      formInfo.value.data.goodsLocationId
    if (row.batchNumber) {
      selectBatchInfo.value.query.queryMap.batchNumber = {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: row.batchNumber,
      }
    } else {
      selectBatchInfo.value.query.queryMap.batchNumber = {
        queryType: 'NULL',
        queryCategory: 'AND',
        value: '',
      }
    }
    if (row.validityDate) {
      selectBatchInfo.value.query.queryMap.validityDate = {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: row.validityDate,
      }
    } else {
      selectBatchInfo.value.query.queryMap.validityDate = {
        queryType: 'NULL',
        ignoreEmptyValue: false,
        queryCategory: 'AND',
        value: null,
      }
    }
    if (row.productionDate) {
      selectBatchInfo.value.query.queryMap.productionDate = {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: row.productionDate,
      }
    } else {
      selectBatchInfo.value.query.queryMap.productionDate = {
        queryType: 'NULL',
        ignoreEmptyValue: false,
        queryCategory: 'AND',
        value: null,
      }
    }
    if (row.codeType === 2 || row.codeType === 3) {
      selectBatchInfo.value.query.queryParams.groupField = groupField1.value
    } else {
      selectBatchInfo.value.query.queryParams.groupField = groupField2.value
    }
    selectBatchInfo.value.popoVisible = true
    clearTimeout(timer)
  }, 0)
}
function batchPopoHide() {
  selectBatchInfo.value.popoVisible = false
}
function selectBatchBack(obj) {
  let index = selectBatchInfo.value.index
  let data = proxy.$fn.deepClone(tableInfo.value.data[index])
  obj = countData(obj)
  obj.cargoStockId = obj.id
  if (obj.codeType === 2 || obj.codeType === 3) {
    obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
    obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
  }
  obj.targetLocationNo = data.targetLocationNo
  obj.targetLocationTypeValue = data.targetLocationTypeValue
  obj.targetGoodsLocationId = data.targetGoodsLocationId
  tableInfo.value.data[index] = proxy.$fn.deepClone(obj)
  tableInfo.value.data[index].details = [proxy.$fn.deepClone(obj)]
  tableInfo.value.data[index].groupKey = data.groupKey
  if (obj.codeType === 2 || obj.codeType === 3) {
    setTableStockAv(tableInfo.value.data, data.groupKey)
  }
}
function selectBatchBackList(data) {
  data.forEach((item, index) => {
    item.cargoStockId = item.id
  })
  let row = selectBatchInfo.value.row
  let index = selectBatchInfo.value.index
  data.forEach((item) => {
    item = countData(item)
    item.targetLocationNo = row.targetLocationNo
    item.targetLocationTypeValue = row.targetLocationTypeValue
    item.targetGoodsLocationId = row.targetGoodsLocationId
    if (row.codeType === 2 || row.codeType === 3) {
      item._key = '--'
    }
  })
  console.log(data)
  let groupData = _.groupBy(data, '_key')
  let groupKeys = Object.keys(groupData)
  let groupKeysIn = []
  // tableInfo.value.data.forEach((item) => {
  //   if (item.groupKey === row.groupKey) {
  //     if (item._key) {
  //       if (groupKeys.includes(item._key)) {
  //         groupKeysIn.push(item._key)
  //         item.details = item.details.concat(groupData[item._key])
  //         item = countQty(item)
  //       }
  //     }
  //   }
  // })
  let list = []
  if (groupKeysIn.length) {
    groupKeys.forEach((item) => {
      if (!groupKeysIn.includes(item)) {
        let groupDataItem = groupData[item]
        let obj = proxy.$fn.deepClone(groupDataItem[0])
        obj.details = proxy.$fn.deepClone(groupDataItem)
        obj.groupKey = row.groupKey
        obj = countQty(obj)
        if (obj.codeType === 2 || obj.codeType === 3) {
          obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
          obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
        }
        list.push(obj)
      }
    })
  } else {
    let values = Object.values(groupData)
    values.forEach((item) => {
      item.forEach((el) => {
        if (!el.depotStockId) {
          el.depotStockId = row.depotStockId
        }
      })
      let obj = proxy.$fn.deepClone(item[0])
      obj.details = proxy.$fn.deepClone(item)
      obj.groupKey = row.groupKey
      obj = countQty(obj)
      if (obj.codeType === 2 || obj.codeType === 3) {
        obj.stockAvailableQty = obj.mergeStockAvailableQty || 0
        obj.stockAvailableCalcQty = obj.mergeStockAvailableCalcQty || 0
      }
      list.push(obj)
    })
  }
  if (list.length) {
    let newData = tableInfo.value.data[index]
    let leftList = []
    if (newData._key) {
      leftList = tableInfo.value.data.slice(0, index + 1)
    } else {
      leftList = tableInfo.value.data.slice(0, index)
    }
    let rightList = tableInfo.value.data.slice(index + 1)
    tableInfo.value.data = leftList.concat(list).concat(rightList)
  }
  if (row.codeType === 2 || row.codeType === 3) {
    setTableStockAv(tableInfo.value.data, row.groupKey)
  }
}
function countQty(data) {
  let largeUnitQty = 0
  let smallUnitQty = 0
  let calcQty = 0
  data.details.forEach((el) => {
    largeUnitQty = proxy.$fn.accAdd(largeUnitQty, el.largeUnitQty || 0)
    smallUnitQty = proxy.$fn.accAdd(smallUnitQty, el.smallUnitQty || 0)
    calcQty = proxy.$fn.accAdd(calcQty, el.calcQty || 0)
  })
  data.largeUnitQty = largeUnitQty
  data.smallUnitQty = smallUnitQty
  data.calcQty = calcQty
  data.qty = proxy.$fn.accDiv(calcQty, data.unitConvertCoefficient || 1)
  return data
}
function batchKeyDown(index) {
  proxy.$nextTick(() => {
    if (index < 0) {
      let className = 'batchKey' + selectBatchInfo.value.index
      setVal(className)
      selectBatchInfo.value.popoVisible = false
      return
    }
    let className = 'batchKey' + selectBatchInfo.value.index
    let batchKeyDom = document
      .getElementsByClassName(className)[0]
      .querySelector('.el-input__inner')
    batchKeyDom.blur()
  })
}
//批量设置货位
function setLocationNo() {
  setGoodsInfo.value.query.idNotIn = formInfo.value.data.goodsLocationId
  setGoodsInfo.value.query.depotId = formInfo.value.data.depotId
  selectGoodsInfo.value.popoVisible = false
  setGoodsInfo.value.visible = true
}
function setGoodsCallback(row) {
  let ids = tableInfo.value.selections.map((item) => item.groupKey)
  tableInfo.value.data.forEach((item) => {
    if (ids.includes(item.groupKey)) {
      item.targetLocationNo = row.locationNo
      item.targetGoodsLocationId = row.id
      item.targetLocationTypeValue = row.locationTypeValue
      item.targetLocationType = row.locationType
      item.details?.forEach((el) => {
        el.targetLocationNo = row.locationNo
        el.targetGoodsLocationId = row.id
        el.targetLocationTypeValue = row.locationTypeValue
        el.targetLocationType = row.locationType
      })
    }
  })
}
function goodsSearch(row, index, event) {
  if (!formInfo.value.data.depotId) {
    proxy.$message({
      message: '请选择转移仓库',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  selectGoodsInfo.value.query.depotId = formInfo.value.data.depotId
  // 转出货位
  if (!row) {
    selectGoodsInfo.value.query.idNotIn = ''
    selectGoodsInfo.value.row = null
    selectGoodsInfo.value.index = null
  } else {
    // 转入货位
    selectGoodsInfo.value.query.idNotIn = formInfo.value.data.goodsLocationId
    selectGoodsInfo.value.row = row
    selectGoodsInfo.value.index = index
    selectGoodsInfo.value.refresh = Math.random()
    targetLocationNoRef.value = proxy.$refs['targetLocationNoRef' + index]
  }
  if (event === 'enter') {
    goodsKeyDown()
    selectGoodsInfo.value.visible = false
    selectGoodsInfo.value.popoVisible = true
  } else {
    selectGoodsInfo.value.visible = true
    selectGoodsInfo.value.popoVisible = false
  }
}
function selectGoodsCallback(row) {
  const tbIndex = selectGoodsInfo.value.index
  // 若点击的是转入货位
  if (tbIndex || tbIndex === 0) {
    tableInfo.value.data.forEach((item, index) => {
      if (tbIndex === index) {
        item.targetLocationNo = row.locationNo
        item.targetGoodsLocationId = row.id
        item.targetLocationTypeValue = row.locationTypeValue
        item.targetLocationType = row.locationType
        item.details?.forEach((el) => {
          el.targetLocationNo = row.locationNo
          el.targetGoodsLocationId = row.id
          el.targetLocationTypeValue = row.locationTypeValue
          el.targetLocationType = row.locationType
        })
      }
    })
    return
  }
  // 若点击的是转出货位
  if (row) {
    formInfo.value.data.locationNo = row.locationNo
    formInfo.value.data.goodsLocationId = row.id
    formInfo.value.data.locationTypeValue = row.locationTypeValue
    scanInfo.value.query.queryParams.goodsLocationId = row.id
    scanInfo.value.query.queryParams.locationNo = row.locationNo
  } else {
    formInfo.value.data.locationNo = ''
    formInfo.value.data.goodsLocationId = ''
    formInfo.value.data.locationTypeValue = ''
    scanInfo.value.query.queryParams.goodsLocationId = ''
    scanInfo.value.query.queryParams.locationNo = ''
  }
  tableInfo.value.data = [
    {
      emptyRowType: '1',
      productKeyword: '',
      batchKeyword: '',
      id: new Date().getTime() + (1 + Math.random()),
    },
  ]
}
function goodsKeyDown(index) {
  proxy.$nextTick(() => {
    if (index < 0) {
      let className = 'targetLocationNo' + selectGoodsInfo.value.index
      setVal(className)
      selectGoodsInfo.value.popoVisible = false
      return
    }
    let className = 'targetLocationNo' + selectGoodsInfo.value.index
    let targetLocationNoDom = document
      .getElementsByClassName(className)[0]
      .querySelector('.el-input__inner')
    targetLocationNoDom.blur()
  })
}
function goodsPopoHide() {
  selectGoodsInfo.value.popoVisible = false
}
//选择出库仓库
function selectExportDepot() {
  selectExportDepotInfo.value.query.idNot = formInfo.value.data.depotId
  selectExportDepotInfo.value.visible = true
}
function selectExportDepotCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.value.data.depotId = data.id
    formInfo.value.data.depotName = data.name
    formInfo.value.data.locationTypeValue = ''
    formInfo.value.data.locationNo = ''
    formInfo.value.data.goodsLocationId = ''
    selectProductInfo.value.query.queryMap.depotId.value = data.id
    selectBatchInfo.value.query.queryMap.depotId.value = data.id
    individualInfo.value.leftQuery.queryMap.depotId.value = data.id
    tableInfo.value.data = [
      {
        emptyRowType: '1',
        productKeyword: '',
        batchKeyword: '',
        id: new Date().getTime() + (1 + Math.random()),
      },
    ]
    scanInfo.value.query.queryParams.depotId = data.id
  } else {
    formInfo.value.data.depotId = ''
    formInfo.value.data.depotName = ''
    formInfo.value.data.locationTypeValue = ''
    formInfo.value.data.locationNo = ''
    formInfo.value.data.goodsLocationId = ''
    selectProductInfo.value.query.queryMap.depotId.value = ''
    selectBatchInfo.value.query.queryMap.depotId.value = ''
    individualInfo.value.leftQuery.queryMap.depotId.value = ''
    tableInfo.value.data = [
      {
        emptyRowType: '1',
        productKeyword: '',
        batchKeyword: '',
        id: new Date().getTime() + (1 + Math.random()),
      },
    ]
    scanInfo.value.query.queryParams.depotId = ''
  }
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    return parseInt(row.stockAvailableCalcQty / row.unitConvertCoefficient)
  } else {
    return row.stockAvailableQty
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.stockAvailableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let largeUnitQty = parseInt(
    row.stockAvailableCalcQty / row.unitConvertCoefficient
  )
  if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
    if (largeUnitQty > 0 && e === largeUnitQty) {
      let smallUnitQty = parseInt(
        row.stockAvailableCalcQty % row.unitConvertCoefficient
      )
      if (row.smallUnitQty > smallUnitQty) {
        row.smallUnitQty = smallUnitQty
      }
    }
  }
  if (row.codeType === 1 || row.codeType === 4) {
    row.calcQty = proxy.$fn.accAdd(
      proxy.$fn.accMul(row.largeUnitQty || 0, row.unitConvertCoefficient || 1),
      row.smallUnitQty || 0
    )
    row.qty = proxy.$fn.accDiv(
      row.calcQty || 0,
      row.unitConvertCoefficient || 1
    )
    row.details[0].largeUnitQty = row.largeUnitQty
    row.details[0].smallUnitQty = row.smallUnitQty
    row.details[0].calcQty = row.calcQty
    row.details[0].qty = row.qty
  }
}
function changeSmall(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  if (row.codeType === 1 || row.codeType === 4) {
    row.calcQty = proxy.$fn.accAdd(
      proxy.$fn.accMul(row.largeUnitQty || 0, row.unitConvertCoefficient || 1),
      row.smallUnitQty || 0
    )
    row.qty = proxy.$fn.accDiv(
      row.calcQty || 0,
      row.unitConvertCoefficient || 1
    )
    row.details[0].largeUnitQty = row.largeUnitQty
    row.details[0].smallUnitQty = row.smallUnitQty
    row.details[0].calcQty = row.calcQty
    row.details[0].qty = row.qty
  }
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function countData(data) {
  if (data.stockAvailableCalcQty > data.unitConvertCoefficient) {
    data.calcQty = data.unitConvertCoefficient
    data.largeUnitQty = parseInt(data.calcQty / data.unitConvertCoefficient)
    data.smallUnitQty = parseInt(data.calcQty % data.unitConvertCoefficient)
    data.qty = proxy.$fn.accDiv(data.calcQty, data.unitConvertCoefficient)
  } else {
    data.calcQty = data.stockAvailableCalcQty
    data.largeUnitQty = parseInt(data.calcQty / data.unitConvertCoefficient)
    data.smallUnitQty = parseInt(data.calcQty % data.unitConvertCoefficient)
    data.qty = proxy.$fn.accDiv(data.calcQty, data.unitConvertCoefficient)
  }
  data._key =
    data.storeBatchNumber +
    '-' +
    data.supplierId +
    '-' +
    data.price +
    '-' +
    data.isConsignBusiness
  if (data.codeType === 2 || data.codeType === 3) {
    data._key = '--'
  }
  return data
}
function tableCellClassName({ column, row }) {
  if (row.isChoice && column.property === 'qty') {
    return 'success-row'
  } else {
    return ''
  }
}
function addBucth(row, index) {
  batchNumberSearch(row, index)
}
function copyBucth(row, index) {
  const leftList = []
  const rightList = []
  const deepRow = proxy.$fn.deepClone(row)
  tableInfo.value.data.forEach((item, idx) => {
    if (idx <= index) {
      leftList.push(item)
    } else {
      rightList.push(item)
    }
  })
  deepRow.targetGoodsLocationId = ''
  deepRow.targetLocationNo = ''
  deepRow.targetLocationTypeValue = ''
  deepRow.cloneIndex = Math.random()
  tableInfo.value.data = [...leftList, deepRow, ...rightList]
}
function removeProduct() {
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      let groupKeys = tableInfo.value.selections.map((item) => item.groupKey)
      tableInfo.value.data = tableInfo.value.data.filter(
        (item) => !groupKeys.includes(item.groupKey)
      )
      if (!tableInfo.value.data.length) {
        tableInfo.value.data = [
          {
            emptyRowType: '1',
            productKeyword: '',
            batchKeyword: '',
            id: new Date().getTime() + (1 + Math.random()),
          },
        ]
      } else {
        let index = tableInfo.value.data.findIndex(
          (item) => item.emptyRowType === '1'
        )
        if (index === -1) {
          tableInfo.value.data.push({
            emptyRowType: '1',
            productKeyword: '',
            batchKeyword: '',
            id: new Date().getTime() + (1 + Math.random()),
          })
        }
      }
      const data = proxy.$fn.deepClone(tableInfo.value.data)
      tableInfo.value.data = []
      proxy.$nextTick(() => {
        tableInfo.value.data = data
      })
    })
}
function downloadTemplate() {
  exportTemplateExcel('wms_transfer_import').then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function beforeUpload(file) {
  uploadInfo.value.action =
    import.meta.env.VITE_APP_BASE_API +
    '/wms/transferOrder/import/excel/' +
    formInfo.value.data.goodsLocationId
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: 'rgba(255,255,255,.4)',
  })
  let fileType = ['xlsx']
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size
  let isFileType = fileType.some(
    (type) => file.name.split('.')[file.name.split('.').length - 1] === type
  )
  const isLt = file.size / 1024 / 1024 < fileSize
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(' / ')} 格式文件!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    })
    uploadInfo.value.loading.close()
    return false
  }
  return isFileType && isLt
}
function uploadSuccess(resp) {
  uploadInfo.value.loading.close()
  if (resp && resp.success) {
    proxy.$message.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    })
    // resp.data.forEach((item) => {
    //   item.largeUnitQty = item.qty
    //   item.smallUnitQty = item.qty
    // })

    setTableData(resp.data)
  } else {
    proxy.$message.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    })
  }
}
function uploadError(err) {
  if (err) {
    proxy.$message.error({
      message: '系统错误',
      duration: 3000,
      showClose: true,
    })
  }
  uploadInfo.value.loading.close()
}
// 用于存储groupKey对应批次数量
const groupKeyMap = ref({})
function setSuplierIdMap() {
  let _data = tableInfo.value.data.filter((element) => {
    return element.groupKey
  })
  groupKeyMap.value = _.groupBy(_data, 'groupKey')
}
function removeBatch(row, index) {
  if (row.codeType) {
    if (
      groupKeyMap.value[row.groupKey] &&
      groupKeyMap.value[row.groupKey]?.length > 1
    ) {
      tableInfo.value.data = tableInfo.value.data.filter(
        (item) => ![row].includes(item)
      )
    } else {
      tableInfo.value.data[index] = {
        commonName: row.commonName,
        productCode: row.productCode,
        groupKey: row.groupKey,
        standard: row.standard,
        brandName: row.brandName,
        brandId: row.brandId,
        unitName: row.unitName,
        unitId: row.unitId,
        codeTypeValue: row.codeTypeValue,
        codeType: row.codeType,
        batchNumber: row.batchNumber,
        productionDate: row.productionDate,
        validityDate: row.validityDate,
        depotStockId: row.depotStockId,
        productId: row.productId,
        orgId: row.orgId,
        emptyRowType: '2',
      }
    }
  }
}
function individualDetails(row, index) {
  let groupKeyList = tableInfo.value.data.filter(
    (item) => item.groupKey === row.groupKey
  )
  let leftIds = []
  let groupConcatId = ''
  let isRequest = false
  if (!row.details && row.groupConcatIds && row.groupConcatCargoStockIds) {
    isRequest = true
  }
  groupConcatId = row.groupConcatIds ? row.groupConcatIds : ''
  individualInfo.value.row = row
  individualInfo.value.details = row.details
  if (groupKeyList.length) {
    groupKeyList.forEach((item) => {
      if (!item.details) {
        leftIds.push(item.groupConcatCargoStockIds)
      } else {
        item.details?.forEach((el) => {
          leftIds.push(el.cargoStockId)
        })
      }
    })
  }
  individualInfo.value.index = index
  individualInfo.value.leftQuery.queryMap.orgId.value = row.orgId
  individualInfo.value.leftQuery.queryMap.productId.value = row.productId
  individualInfo.value.leftQuery.queryMap.goodsLocationId.value =
    formInfo.value.data.goodsLocationId
  if (row.batchNumber) {
    individualInfo.value.leftQuery.queryMap.batchNumber = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.batchNumber,
    }
  } else {
    individualInfo.value.leftQuery.queryMap.batchNumber = {
      queryType: 'NULL',
      queryCategory: 'AND',
      value: '',
    }
  }
  if (row.validityDate) {
    individualInfo.value.leftQuery.queryMap.validityDate = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.validityDate,
    }
  } else {
    individualInfo.value.leftQuery.queryMap.validityDate = {
      queryType: 'NULL',
      ignoreEmptyValue: false,
      queryCategory: 'AND',
      value: null,
    }
  }
  if (row.productionDate) {
    individualInfo.value.leftQuery.queryMap.productionDate = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.productionDate,
    }
  } else {
    individualInfo.value.leftQuery.queryMap.productionDate = {
      queryType: 'NULL',
      ignoreEmptyValue: false,
      queryCategory: 'AND',
      value: null,
    }
  }
  // individualInfo.value.leftQuery.queryMap.batchNumber.value =
  //   row.batchNumber || ''
  // individualInfo.value.leftQuery.queryMap.validityDate.value =
  //   row.validityDate || ''
  // individualInfo.value.leftQuery.queryMap.productionDate.value =
  //   row.productionDate || ''
  individualInfo.value.leftQuery.queryMap.id.value = leftIds.length
    ? leftIds.toString()
    : ''
  individualInfo.value.rightQuery.queryMap.id.value = props.orderId
    ? groupConcatId
    : ''
  if (row.codeType === 2 || row.codeType === 3) {
    individualInfo.value.leftQuery.queryParams.groupField = groupField1.value
  } else {
    individualInfo.value.leftQuery.queryParams.groupField = groupField2.value
  }
  individualInfo.value.isRequest = isRequest
  individualInfo.value.rightQuery.queryMap.orderId.value = props.orderId
  individualInfo.value.visible = true
}
function individualCallback(data) {
  console.log(data)
  let index = individualInfo.value.index
  let row = individualInfo.value.row
  data.forEach((item, index) => {
    item.targetLocationNo = row.targetLocationNo
    item.targetGoodsLocationId = row.targetGoodsLocationId
    item.targetLocationTypeValue = row.targetLocationTypeValue
    // item.cargoStockId = item.id
    item._key = '--' //codeType为2和3的时候才有个体详情，唯一码的需要置空
  })
  if (data.length) {
    let groupData = _.groupBy(data, '_key')
    let groupKeys = Object.keys(groupData)
    let groupKeysIn = []
    tableInfo.value.data = tableInfo.value.data.filter((item, idx) => {
      if (item.groupKey === row.groupKey && idx === index) {
        if (item._key) {
          return groupKeys.includes(item._key)
        } else {
          return item
        }
      } else {
        return item
      }
    })
    tableInfo.value.data.forEach((item, idx) => {
      if (item.groupKey === row.groupKey && idx === index) {
        if (item._key) {
          if (groupKeys.includes(item._key)) {
            groupKeysIn.push(item._key)
            item.details = groupData[item._key]
            item = countQty(item)
          }
        }
      }
    })
    let list = []
    if (groupKeysIn.length) {
      groupKeys.forEach((item) => {
        if (!groupKeysIn.includes(item)) {
          let groupDataItem = groupData[item]
          let obj = proxy.$fn.deepClone(groupDataItem[0])
          obj.details = proxy.$fn.deepClone(groupDataItem)
          obj.groupKey = row.groupKey
          obj = countQty(obj)
          if (obj.codeType === 2 || obj.codeType === 3) {
            obj.stockAvailableQty =
              obj.mergeStockAvailableQty || row.stockAvailableQty || 0
            obj.stockAvailableCalcQty =
              obj.mergeStockAvailableCalcQty || row.stockAvailableCalcQty || 0
          }
          list.push(obj)
        }
      })
    } else {
      let values = Object.values(groupData)
      values.forEach((item) => {
        // item.forEach((el) => {
        //   el.depotStockId = row.depotStockId
        // })
        let obj = proxy.$fn.deepClone(item[0])
        obj.details = proxy.$fn.deepClone(item)
        obj.groupKey = row.groupKey
        obj = countQty(obj)
        if (obj.codeType === 2 || obj.codeType === 3) {
          obj.stockAvailableQty =
            obj.mergeStockAvailableQty || row.stockAvailableQty || 0
          obj.stockAvailableCalcQty =
            obj.mergeStockAvailableCalcQty ||
            row.mergeStockAvailableCalcQty ||
            0
        }
        list.push(obj)
      })
    }
    if (list.length) {
      let newData = tableInfo.value.data[index]
      let leftList = []
      if (newData?._key) {
        leftList = tableInfo.value.data.slice(0, index + 1)
      } else {
        leftList = tableInfo.value.data.slice(0, index)
      }
      let rightList = tableInfo.value.data.slice(index + 1)
      tableInfo.value.data = leftList.concat(list).concat(rightList)
    }
  } else {
    tableInfo.value.data[index] = {
      commonName: row.commonName,
      productCode: row.productCode,
      groupKey: row.groupKey,
      standard: row.standard,
      brandName: row.brandName,
      brandId: row.brandId,
      unitName: row.unitName,
      unitId: row.unitId,
      codeTypeValue: row.codeTypeValue,
      codeType: row.codeType,
      batchNumber: row.batchNumber,
      productionDate: row.productionDate,
      validityDate: row.validityDate,
      depotStockId: row.depotStockId,
      productId: row.productId,
      orgId: row.orgId,
      emptyRowType: '',
      targetGoodsLocationId: row.targetGoodsLocationId,
      targetLocationNo: row.targetLocationNo,
      targetLocationTypeValue: row.targetLocationTypeValue,
    }
    console.log(tableInfo.value.data)
    // tableInfo.value.data = tableInfo.value.data.filter((item) => {
    //   if (row.groupKey === item.groupKey) {
    //     return item.emptyRowType === '2'
    //   } else {
    //     return item
    //   }
    // })
  }
  setTableStockAv(tableInfo.value.data, row.groupKey)
  let emptyIndex = tableInfo.value.data.findIndex(
    (item) => item.emptyRowType === '1'
  )
  if (emptyIndex === -1) {
    tableInfo.value.data.push({
      emptyRowType: '1',
      productKeyword: '',
      batchKeyword: '',
      id: new Date().getTime() + (1 + Math.random()),
    })
  }
}
function setTableStockAv(data, rowGroupKey) {
  let tempGroupKeys
  let stockAv
  data.forEach((item) => {
    if (item.groupKey === tempGroupKeys && item.groupKey === rowGroupKey) {
      item.stockAvailableQty = stockAv
    }
    tempGroupKeys = item.groupKey
    stockAv = item.stockAvailableQty
  })
}
async function onCallBackScanData(data, callback) {
  let { mergeDetail, detail } = data
  let str = ''
  mergeDetail = mergeDetail[0]
  mergeDetail.mergeStockAvailableQty = mergeDetail.stockAvailableQty
  mergeDetail.mergeStockAvailableCalcQty = mergeDetail.stockAvailableCalcQty
  detail.mergeStockAvailableQty = mergeDetail.stockAvailableQty
  detail.mergeStockAvailableCalcQty = mergeDetail.stockAvailableCalcQty
  let sysGroupArr = []
  if (mergeDetail.codeType === 2 || mergeDetail.codeType === 3) {
    sysGroupArr = groupField1.value.split(',')
  } else {
    sysGroupArr = groupField2.value.split(',')
  }
  sysGroupArr.forEach((item) => {
    if (
      item !== 'price' &&
      item !== 'supplierId' &&
      item !== 'storeBatchNumber' &&
      item !== 'targetGoodsLocationId' &&
      item !== 'depotId' &&
      item !== 'isConsignBusiness'
    ) {
      if (item === 'productionDate' || item === 'validityDate') {
        str = str + (mergeDetail[item] || '1900-01-01') + ''
      } else {
        str = str + mergeDetail[item] + ''
      }
    }
  })
  tableInfo.value.data.some((item) => {
    if (item.groupKey?.includes(str)) {
      str = item.groupKey
    }
  })
  detail._key =
    mergeDetail.storeBatchNumber +
    '-' +
    mergeDetail.supplierId +
    '-' +
    mergeDetail.price +
    '-' +
    mergeDetail.isConsignBusiness
  if (mergeDetail.codeType === 2 || mergeDetail.codeType === 3) {
    detail._key = '--'
  }
  mergeDetail.groupKey = str
  let unitConvertCoefficient = detail.unitConvertCoefficient || 1
  if (tableInfo.value.data && tableInfo.value.data.length) {
    tableInfo.value.data.forEach((item) => {
      item.isChoice = false
    })
    let list = tableInfo.value.data.filter(
      (item) => item.groupKey === mergeDetail.groupKey
    )
    if (list.length) {
      let index = tableInfo.value.data.findLastIndex(
        (item) =>
          item.groupKey === mergeDetail.groupKey &&
          item._key &&
          item._key === detail._key
      )
      if (index > -1) {
        if (
          tableInfo.value.data[index].calcQty ===
          tableInfo.value.data[index].stockAvailableCalcQty
        ) {
          callback(true)
          return
        }
        if (
          props.orderId &&
          !tableInfo.value.data[index].details &&
          tableInfo.value.data[index].groupConcatCargoStockIds &&
          tableInfo.value.data[index].groupConcatIds
        ) {
          await getIndividualRight(
            tableInfo.value.data[index].groupConcatIds
          ).then((res) => {
            tableInfo.value.data[index].details = res
          })
        }
        let haveIndex = tableInfo.value.data[index].details.findLastIndex(
          (item) => item.depotStockId == detail.depotStockId
        )
        if (detail.codeType === 2 || detail.codeType === 3) {
          if (haveIndex > -1) {
            callback(true)
          } else {
            setLocationData(detail, tableInfo.value.data[index])
            tableInfo.value.data[index].details.push(detail)
            tableInfo.value.data[index] = countQty(tableInfo.value.data[index])
            tableInfo.value.data[index].isChoice = true
          }
        } else if (detail.codeType === 4) {
          let num = proxy.$fn.Subtr(
            tableInfo.value.data[index].stockAvailableCalcQty,
            tableInfo.value.data[index].calcQty
          )
          if (haveIndex > -1) {
            if (num > unitConvertCoefficient) {
              tableInfo.value.data[index].details[haveIndex].calcQty =
                proxy.$fn.accAdd(
                  tableInfo.value.data[index].details[haveIndex].calcQty || 0,
                  1
                )
            } else {
              tableInfo.value.data[index].details[haveIndex].calcQty =
                tableInfo.value.data[index].details[
                  haveIndex
                ].stockAvailableCalcQty
            }
            tableInfo.value.data[index].details[haveIndex].largeUnitQty =
              parseInt(
                tableInfo.value.data[index].details[haveIndex].calcQty /
                  unitConvertCoefficient
              )
            tableInfo.value.data[index].details[haveIndex].smallUnitQty =
              parseInt(
                tableInfo.value.data[index].details[haveIndex].calcQty %
                  unitConvertCoefficient
              )
            tableInfo.value.data[index].details[haveIndex].qty =
              proxy.$fn.accDiv(
                tableInfo.value.data[index].details[haveIndex].calcQty,
                unitConvertCoefficient
              )
            tableInfo.value.data[index] = countQty(tableInfo.value.data[index])
            tableInfo.value.data[index].isChoice = true
          } else {
            setLocationData(detail, tableInfo.value.data[index])
            tableInfo.value.data[index].details.push(detail)
            tableInfo.value.data[index] = countQty(tableInfo.value.data[index])
            tableInfo.value.data[index].isChoice = true
          }
        }
      } else {
        let newIndex = tableInfo.value.data.findLastIndex(
          (item) =>
            item.groupKey === mergeDetail.groupKey &&
            item.emptyRowType &&
            item.emptyRowType === '2'
        )
        if (newIndex > -1) {
          mergeDetail.details = [detail]
          mergeDetail._key = detail._key
          mergeDetail = countQty(mergeDetail)
          tableInfo.value.data[newIndex] = mergeDetail
        } else {
          let spliceIndex = tableInfo.value.data.findIndex(
            (item) => item.depotStockId == list[list.length - 1].depotStockId
          )
          mergeDetail.details = [detail]
          mergeDetail._key = detail._key
          mergeDetail = countQty(mergeDetail)
          tableInfo.value.data.splice(spliceIndex, 0, mergeDetail)
        }
      }
    } else {
      let list = tableInfo.value.data.filter((item) => item.cargoStockId)
      mergeDetail.details = [detail]
      mergeDetail._key = detail._key
      console.log(list)
      if (list.length) {
        let index = tableInfo.value.data.findLastIndex(
          (item) => item.cargoStockId === list[list.length - 1].cargoStockId
        )
        console.log(index)
        tableInfo.value.data.splice(index + 1, 0, mergeDetail)
      } else {
        tableInfo.value.data.unshift(mergeDetail)
      }
      mergeDetail = countQty(mergeDetail)
      callback(false)
    }
  }
  setSuplierIdMap()
}
function setLocationData(detail, row) {
  detail.targetGoodsLocationId = row.targetGoodsLocationId
  detail.targetLocationNo = row.targetLocationNo
  detail.targetLocationType = row.targetLocationType
  detail.targetLocationTypeValue = row.targetLocationTypeValue
}
function getIndividualRight(ids) {
  return new Promise((resolve, reject) => {
    let param = {
      customizeUserVO: individualInfo.value.rightVo,
      queryMap: {
        id: {
          queryType: 'IN',
          queryCategory: 'AND',
          value: ids,
        },
        orderId: {
          queryType: 'EQUALS',
          queryCategory: 'AND',
          value: props.orderId,
        },
      },
      queryParams: {},
    }
    getConsumeOrderDetailCustomizeListAll(param).then((resp) => {
      if (resp && resp.success) {
        let data = resp.data
        data.forEach((item) => {
          item.isChoice = false
        })
        resolve(data)
      } else {
        reject()
      }
    })
  })
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    const newDetailsList = tableInfo.value.data.filter((row) => row.productId)
    if (!newDetailsList.length) {
      proxy.$message({
        message: '请添加有效的产品',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let emptyDetails = newDetailsList
      .filter((item) => item.emptyRowType === '2')
      .map((item) => item.commonName)
    if (emptyDetails.length) {
      proxy.$message({
        message: '请添产品【' + emptyDetails + '】的批次信息',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let commonName = newDetailsList
      .filter((item) => item.calcQty > item.stockAvailableCalcQty)
      .map((item) => item.commonName)
    if (commonName.length) {
      proxy.$message({
        message: `产品【${commonName}】的转移数量不能大于可用数量，请修改`,
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let newDetails = newDetailsList.filter((item) => item.calcQty > 0)
    reSave(newDetails)
  })
}
function reSave(newDetails) {
  const data = formInfo.value.data
  let details = proxy.$fn.filterBlacklist(newDetails)
  data.mergeDetails = details
  const validateApi = props.orderId ? updateTransferOrder : addTransferOrder
  validateApi(data).then((resp) => {
    if (resp && resp.success) {
      showDialog.value = false
      emit('returnModify', false)
      tableInfo.value.data = []
      initTableRow()
      tableInfo.value.map = new Map()
    }
  })
}
function validateExpire(list = []) {
  let currentDate = moment().format('YYYY-MM-DD')
  let msg = ''
  list.forEach((item, index) => {
    if (item.validityDate && moment(item.validityDate).isBefore(currentDate)) {
      msg = msg + `第【${index + 1}】行产品【${item.commonName}】已过期，<br>`
    }
  })
  return msg
}
function getMain() {
  transferOrderById(props.orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      scanInfo.value.query.queryParams.depotId = resp.data.depotId
      scanInfo.value.query.queryParams.locationNo = resp.data.locationNo
      scanInfo.value.query.queryParams.goodsLocationId =
        resp.data.goodsLocationId
      scanInfo.value.query.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      selectProductInfo.value.query.queryMap.depotId.value = resp.data.depotId
      selectProductInfo.value.query.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      selectBatchInfo.value.query.queryMap.depotId.value = resp.data.depotId
      selectBatchInfo.value.query.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      individualInfo.value.leftQuery.queryMap.depotId.value = resp.data.depotId
      individualInfo.value.leftQuery.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
      individualInfo.value.rightQuery.queryMap.isConsignBusiness.value =
        resp.data.isConsignBusiness
    }
  })
  filterInfo.value.query.queryMap.orderId.value = props.orderId
  getList()
}
function getList() {
  //修改请求明细信息
  getConsumeOrderDetailCustomizeListAll(filterInfo.value.query).then((resp) => {
    if (resp && resp.success && resp.data.length) {
      let data = resp.data
      // 此方案为临时方案，最好的还是后端直接改而不是前端进行遍历赋值改变
      data.forEach((item) => {
        if (
          item.qty > item.stockAvailableQty &&
          item.codeType !== 2 &&
          item.codeType !== 3
        ) {
          item.qty = item.stockAvailableQty
          item.largeUnitQty = item.stockAvailableQty
          item.calcQty = item.stockAvailableQty
          item.groupSize = item.stockAvailableQty
        }
      })
      setTableData(data)
    }
  })
}
function setTableData(data) {
  data.forEach((row, index) => {
    let str = ''
    tableInfo.value.sysGroup.forEach((item) => {
      if (
        item !== 'price' &&
        item !== 'supplierId' &&
        item !== 'storeBatchNumber' &&
        item !== 'targetGoodsLocationId'
      ) {
        if (item === 'productionDate' || item === 'validityDate') {
          str = str + (row[item] || '1900-01-01') + ''
        } else {
          str = str + row[item] + ''
        }
      }
    })
    row.groupKey = str
    row._key =
      row.storeBatchNumber +
      '-' +
      row.supplierId +
      '-' +
      row.price +
      '-' +
      row.isConsignBusiness
    if (row.codeType === 2 || row.codeType === 3) {
      row._key = '--'
    }
    if (row.codeType === 1 || row.codeType === 4) {
      let detail = proxy.$fn.deepClone(row)
      row.details = [detail]
    }
  })
  tableInfo.value.data = _.orderBy(data, 'groupKey')
  console.log(tableInfo.value.data)
  initTableRow()
}
function initTableRow() {
  tableInfo.value.data.push({
    emptyRowType: '1',
    productKeyword: '',
    batchKeyword: '',
    id: new Date().getTime() + (1 + Math.random()),
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'productBatchStockTransferOrderModify-com.slip.spd.entity.vo.wms.WmsTransferOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let arr = []
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          arr.push({ key, sysGroupLevel: data.detail[key].sysGroupLevel })
        }
      }
      arr = proxy.$fn.getSort(arr, 'sysGroupLevel')
      arr = arr.map((element) => {
        return element.key
      })
      selectBatchInfo.value.query.queryParams.groupField = arr.length
        ? arr.toString()
        : ''
      const groupField1Arr = []
      const sysGroupArr = []
      arr.forEach((item) => {
        if (
          [
            'price',
            'supplierId',
            'storeBatchNumber',
            'isConsignBusiness',
          ].indexOf(item) === -1
        ) {
          groupField1Arr.push(item)
          if (['targetGoodsLocationId'].indexOf(item) === -1) {
            sysGroupArr.push(item)
          }
        }
      })
      groupField1.value = groupField1Arr.toString()
      groupField2.value = arr.toString()
      tableInfo.value.sysGroup = sysGroupArr
      console.log(tableInfo.value.sysGroup)
      if (props.orderId) {
        getMain()
      }
    }
  })
}
function getScanCustomize() {
  let param = {
    tableKey:
      'shelfStockTransferOrderProductBatchScan-com.slip.spd.entity.vo.wms.WmsShelfStockVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      scanInfo.value.query.customizeUserVO = data
    }
  })
}
function getProductCustomize() {
  let param = {
    tableKey:
      'selectProductStockTransferOrder-com.slip.spd.entity.vo.wms.WmsShelfStockVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let arr = []
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          arr.push({
            columnName: data.detail[key].columnName,
            asTbName: data.detail[key].asTbName,
            key: key,
          })
        }
      }
      tableInfo.value.productSysGroup = arr
    }
  })
}
function getIndividualRightCustomize() {
  let param = {
    tableKey:
      'selectProductStockTransferOrderIndividualRight-com.slip.spd.entity.vo.wms.WmsTransferOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      individualInfo.value.rightVo = data
    }
  })
}
getCustomize()
getProductCustomize()
getScanCustomize()
getIndividualRightCustomize()
</script>
<style lang="scss" scoped>
.el-input-search {
  width: 100%;
  height: 100%;
}
.isShow {
  :deep(.el-scrollbar__wrap) {
    overflow: inherit;
  }
}
.el-popper {
  overflow-y: hidden;
}
</style>
<style>
.el-popper {
  max-height: max-content !important;
}
.popover-wrapper {
  height: 385.59px;
}
</style>
